# coding: utf-8
# Author: legend
# @Time： 2021/3/8 下午1:48
from rest_framework.mixins import ListModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from apps.test.models import Questions
from apps.test.serializers.question import QuestionSerializer


def get_params(request):
    """
    ### 将request中的参数提取到一个字典

    :return: 参数字典
    """
    data = request.data
    results = {}
    if isinstance(data, dict):
        for key in data.keys():
            results[key] = data.get(key, None)
    data_get = {k: v[0] if len(v) == 1 else v for k, v in request.GET.lists()}
    results_get = {}
    if isinstance(data_get, dict):
        for key in data_get.keys():
            results_get[key] = data_get.get(key, None)
    results.update(results_get)
    return results


class QuestionsViewSet(ListModelMixin, GenericViewSet):
    queryset = Questions.objects.all()
    serializer_class = QuestionSerializer

    def list(self, request, *args, **kwargs):
        question_type = int(get_params(request).get('type'))
        questions = self.queryset.filter(type=question_type)
        if question_type == 0:
            data = self.serializer_class(instance=questions, many=True).data
        else:
            data = {}
            for question_item in questions:
                if question_item.index not in data.keys():
                    data[question_item.index] = [self.serializer_class(instance=question_item).data]
                else:
                    data[question_item.index].append(self.serializer_class(instance=question_item).data)
            data = data.values()
        return Response(data)
